<template>
  <div class="cart-dialog">
    <div class="cart-content">
      <!-- 购物车列表 -->
      <div v-if="cartItems.length">
        <el-table
          :data="cartItems"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="45" />
          <el-table-column label="商品信息" min-width="300">
            <template #default="{ row }">
              <div class="product-info">
                <el-image 
                  :src="row.image" 
                  :alt="row.name" 
                  fit="cover"
                  @click="viewProduct(row)"
                />
                <span class="product-name" @click="viewProduct(row)">{{ row.name }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="单价" width="100" align="center">
            <template #default="{ row }">
              <span class="price">¥{{ row.price }}</span>
            </template>
          </el-table-column>
          <el-table-column label="数量" width="130" align="center">
            <template #default="{ row }">
              <el-input-number 
                v-model="row.quantity" 
                :min="1"
                :max="99"
                size="small"
                @change="(val) => updateQuantity(row, val)"
              />
            </template>
          </el-table-column>
          <el-table-column label="小计" width="100" align="center">
            <template #default="{ row }">
              <span class="subtotal">¥{{ (row.price * row.quantity).toFixed(2) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80" align="center">
            <template #default="{ row }">
              <el-popconfirm
                title="确定要删除这个商品吗？"
                @confirm="removeItem(row)"
              >
                <template #reference>
                  <el-button 
                    type="danger" 
                    size="small"
                    text
                  >
                    删除
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>

        <!-- 底部结算栏 -->
        <div class="cart-footer">
          <div class="selected-info">
            已选择 <span class="highlight">{{ selectedCount }}</span> 件商品
          </div>
          <div class="total-price">
            合计：<span>¥{{ totalPrice.toFixed(2) }}</span>
          </div>
          <el-button 
            type="danger"
            :disabled="!selectedCount"
            @click="checkout"
            size="large"
          >
            结算 ({{ selectedCount }})
          </el-button>
        </div>
      </div>

      <!-- 空购物车提示 -->
      <el-empty v-else>
        <template #image>
          <el-icon :size="60" color="#909399"><ShoppingCart /></el-icon>
        </template>
        <template #description>
          <p>购物车还是空的</p>
        </template>
        <el-button type="primary" @click="$emit('close')">
          去逛逛
        </el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ShoppingCart } from '@element-plus/icons-vue'

const emit = defineEmits(['close', 'view-product'])
const router = useRouter()

const cartItems = ref([
  {
    id: 1,
    name: "商品1",
    price: 99.99,
    quantity: 1,
    image: "https://via.placeholder.com/100",
    selected: false
  },
  {
    id: 2,
    name: "商品2",
    price: 199.99,
    quantity: 2,
    image: "https://via.placeholder.com/100",
    selected: false
  }
])

// 计算属性
const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.selected).length
})

const totalPrice = computed(() => {
  return cartItems.value
    .filter(item => item.selected)
    .reduce((total, item) => total + item.price * item.quantity, 0)
})

// 选中商品变化
const handleSelectionChange = (items) => {
  cartItems.value.forEach(item => {
    item.selected = items.some(selected => selected.id === item.id)
  })
}

// 查看商品详情
const viewProduct = (product) => {
  emit('view-product', product.id)
}

// 更新商品数量
const updateQuantity = async (item, value) => {
  try {
    // TODO: API - 更新购物车商品数量
    // await request.put(`/api/cart/${item.id}`, { quantity: value })
    item.quantity = value
    ElMessage.success('更新成功')
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

// 删除商品
const removeItem = async (item) => {
  try {
    // TODO: API - 删除购物车商品
    // await request.delete(`/api/cart/${item.id}`)
    cartItems.value = cartItems.value.filter(i => i.id !== item.id)
    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.error('删除失败')
  }
}

// 结算
const checkout = () => {
  const selectedItems = cartItems.value.filter(item => item.selected)
  router.push({
    path: '/checkout',
    query: {
      items: selectedItems.map(item => item.id).join(',')
    }
  })
}

// 获取购物车列表
const getCartItems = async () => {
  try {
    // TODO: API - 获取购物车列表
    // const response = await request.get('/api/cart')
    // cartItems.value = response.data.map(item => ({
    //   ...item,
    //   selected: false
    // }))
  } catch (error) {
    ElMessage.error('获取购物车失败')
  }
}

onMounted(() => {
  getCartItems()
})
</script>

<style scoped>
.cart-dialog {
  padding: 10px;
}

.cart-content {
  max-height: calc(90vh - 150px);
  overflow-y: auto;
}

.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-info :deep(.el-image) {
  width: 60px;
  height: 60px;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s;
}

.product-info :deep(.el-image:hover) {
  transform: scale(1.05);
}

.product-name {
  cursor: pointer;
  color: #333;
}

.product-name:hover {
  color: #409EFF;
}

.price, .subtotal {
  color: #ff4444;
  font-weight: 500;
}

.cart-footer {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  gap: 20px;
  padding: 15px 0;
  margin-top: 20px;
  border-top: 1px solid #eee;
}

.selected-info {
  color: #666;
}

.selected-info .highlight {
  color: #ff4444;
  font-weight: bold;
}

.total-price {
  font-size: 16px;
}

.total-price span {
  color: #ff4444;
  font-size: 20px;
  font-weight: bold;
}

:deep(.el-table) {
  --el-table-header-bg-color: #f5f7fa;
}

:deep(.el-input-number.el-input-number--small) {
  width: 100px;
}
</style>